import BaseShape2D from "./BaseShape2D";
import Vector2 from "../maths/Vector2";
import ITransformable from "../interfaces/ITransformable";
import IRenderState from "../interfaces/IRenderState";
import Math2D from "../maths/Math2D";

export default class ConvexPolygon extends BaseShape2D {
    public points: Vector2[];

    public get type(): string {
        return "Polygon";
    }

    public constructor(points: Vector2[]) {
        if (points.length < 3) {
            alert("多边形顶点必须大于3或等于3!!")
            new Error("多边形顶点必须大于3或等于3!!");
        }
        if (Math2D.isConvex(points) === false) {
            alert("当前多边形不是凸多边形!!");
            new Error("当前多边形不是凸多边形!!");
        }
        super();
        this.points = points;
    }
    public hitTest(localPt: Vector2, transform: ITransformable): boolean {
        return Math2D.isPointInPolygon(localPt, this.points);
    }

    public draw(transformable: ITransformable, state: IRenderState, context: CanvasRenderingContext2D): void {
        context.beginPath();
        context.moveTo(this.points[0].x, this.points[0].y);
        for (let i = 1; i < this.points.length; i++) {
            context.lineTo(this.points[i].x, this.points[i].y);
        }
        context.closePath();
        super.draw(transformable, state, context);
    }
}